import { director, JsonAsset } from 'cc';
import { bundleTool } from '../bundleTool';

export default class i18n {
	static langPath = "lang";

	static _language = '';

	static ready: boolean = false;

	/** 语言JSON配置数据 */
	static json: any = {};

	/**
     * 初始化
     * @param language 
     */
	static init(language: string) :boolean{
		i18n.ready = true;
		if(i18n._language===language) return false;
		i18n._language = language;
		i18n.json = null;
		this._getJson();

		return true
	}

	private static _getJson(){
		bundleTool.instance().loadAsyncFromBundle('resources',`${i18n.langPath}/${i18n._language}`, JsonAsset).then((data)=>{
			i18n.json = data.json;
			i18n.updateSceneRenderers();
		});
	}

	/**
     * 翻译数据  key1="user:{0} gold:{1}"
     * @param key "key1&ru,2"
     */
	static t(key: string) {
		if (!i18n.json) {
			return key;
		}

		const vals = key.split('&');
		const searcher = vals[0].split('.');
		let data = i18n.json;

		for (let i = 0; i < searcher.length; i++) {
			data = data[searcher[i]];
			if (!data) {
				return 'no config';
			}
		}

		let val  = data as string;

		if(vals.length>1){
			const parms = vals[1].split(',');

			val = val.replace(/\{(\d)\}/g,function(match, index){
				return parms[index];
			});
		}

		return val;
	}

	static updateSceneRenderers() { // very costly iterations
		const rootNodes = director.getScene()!.children;
		// walk all nodes with localize label and update
		const allLocalizedLabels: any[] = [];

		for (let i = 0; i < rootNodes.length; ++i) {
			const labels = rootNodes[i].getComponentsInChildren('LocalizedLabel');

			Array.prototype.push.apply(allLocalizedLabels, labels);
		}

		for (let i = 0; i < allLocalizedLabels.length; ++i) {
			const label = allLocalizedLabels[i];

			if (!label.node.active) continue;
			label.updateLabel();
		}

		// walk all nodes with localize sprite and update
		const allLocalizedSprites: any[] = [];

		for (let i = 0; i < rootNodes.length; ++i) {
			const sprites = rootNodes[i].getComponentsInChildren('LocalizedSprite');

			Array.prototype.push.apply(allLocalizedSprites, sprites);
		}

		for (let i = 0; i < allLocalizedSprites.length; ++i) {
			const sprite = allLocalizedSprites[i];

			if (!sprite.node.active) continue;
			sprite.updateSprite();
		}
	}
}